<template>
  <div>
    <div class="input-container">
      <el-card>
        <h2 style="text-align:center">{{ title }}</h2>
        <el-alert
          :title="txte"
          type="warning"
          show-icon
          :closable="false"
        />
        <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
      </el-card>
    </div>
  </div>
</template>

<script>
import { reqImportEmployees } from '@/api/character'
import Enum from '@/api/constant/employees'
export default {
  data() {
    return {

    }
  },
  computed: {
    type() {
      return this.$route.query.type
    },
    title() {
      return this.type === 'user' ? '员工导入' : '考勤'
    },
    txte() {
      return this.type === 'user' ? '每次导入仅可以添加1000名员工，姓名、手机号、入职时间、聘用形式必填式' : '考勤'
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 上传成功后使用的函数
    async handleSuccess({ results, header }) {
      // 员工导入
      if (this.type === 'user') {
        // 做一个对照关系的对象
        const rules = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        const res = results.map(item => {
        // console.log(item)
          const obj = {}
          for (const k in item) {
          // console.log(k)// 中文的键
            if (rules[k] === 'formOfEmployment') {
              const o = Enum.hireType.find(sbuItem => sbuItem.value === item[k])
              o ? obj[rules[k]] = o.id : obj[rules[k]] = 0
            } else if (['formOfEmployment', 'correctionTime'].includes(rules[k])) {
              obj[rules[k]] = this.formatExcelDate(item[k], '-')
            } else {
              obj[rules[k]] = item[k]
            }
          }
          return obj
        })
        console.log(res)
        // 1.发送请求
        await reqImportEmployees(res)
        // 2.返回上一页
        this.$router.push('/employees')
      // this.$router.go(-1)// $router.back(),$router.push('/employees')
      }// 考勤导入
      if (this.type === 'att') {
        console.log('考勤导入业务')
      }
    },
    // 时间处理
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style lang="scss">

</style>
